package z_mxsTest.testCleanMutiLangCommonWithList;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 注释清理器 - 清理//和/* * /注释
 */
public class CommentCleaner {
    //private final CommentCleanerApplication mainApp;
    private final LogUtils logUtils;
    // 时间格式化工具，用于日志时间戳
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static final Pattern COMMENT_PATTERN = Pattern.compile(
            "/\\*[\\s\\S]*?\\*\\/|//.*",
            Pattern.CASE_INSENSITIVE
    );

    public CommentCleaner(CommentCleanerApplication mainApp, LogUtils logUtils) {
        //this.mainApp = mainApp;
        this.logUtils = logUtils;
    }

    public void cleanFiles(List<File> files, File rootDir) {
        // 记录开始时间
        long startTime = System.currentTimeMillis();
        String startTimeStr = DATE_FORMAT.format(new Date(startTime));
        logUtils.log("=== 开始清理注释 [" + startTimeStr + "] ===");
        
        int success = 0;
        int fail = 0;

        for (File file : files) {
            try {
                if (cleanSingleFile(file)) {
                    success++;
                    logUtils.log("✅ 成功：" + getRelativePath(rootDir, file));
                } else {
                    success++;
                    logUtils.log("ℹ️ 无需清理：" + getRelativePath(rootDir, file));
                }
            } catch (Exception e) {
                fail++;
                logUtils.log("❌ 失败：" + getRelativePath(rootDir, file) + " - " + e.getMessage());
            }
        }

        // 记录完成时间并计算耗时
        long endTime = System.currentTimeMillis();
        String endTimeStr = DATE_FORMAT.format(new Date(endTime));
        long costSeconds = (endTime - startTime) / 1000;
        
        logUtils.log("=== 清理完成 ===");
        // 核心优化：添加时间、成功和失败统计
        logUtils.log(String.format(
            "清理时间：%s | 总耗时：%ds | 成功：%d个 | 失败：%d个",
            endTimeStr,
            costSeconds,
            success,
            fail
        ));
    }

    private boolean cleanSingleFile(File file) throws IOException {
        String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
        String originalContent = content;

        Matcher matcher = COMMENT_PATTERN.matcher(content);
        content = matcher.replaceAll("");

        if (!content.equals(originalContent)) {
            Files.write(file.toPath(), content.getBytes(StandardCharsets.UTF_8));
            return true;
        }
        return false;
    }

    private String getRelativePath(File rootDir, File file) {
        try {
            return rootDir.toPath().relativize(file.toPath()).toString();
        } catch (Exception e) {
            return file.getAbsolutePath();
        }
    }
}
